<?php
// +----------------------------------------------------------------------
// | 杭州十禾信息科技有限公司
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2015 http://www.shelpe.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: LeePuman <ysyzlsm@163.com>
// +----------------------------------------------------------------------
require_once LIB_PATH . "Library/TaobaoAPI/Curl.php";
class AdgroupAction extends NewzanAction
{
    private static $source = array(
                0 => 'summary',
                1 => 'pc',
                2 => 'wireless'
            );

public function _initialize()
	{
		parent::_initialize();
		$this->userId = $this->me['user_id'];
		// self::$p = array(
		// 	'start_date' => date('Y-m-d', strtotime('-7 day')),
		// 	'end_date' => date('Y-m-d', strtotime('-1 day'))
		// );
		$this->http = new Curl();
	}

    public function manualadd()
    {
    	$adgroup_id = $this->_get('adgroup_id');
    	ParamsCheckUtils::checkNumeric($adgroup_id , '推广组ID不能为空');
    	$this->display();
    }
    
    public function remove()
    {
        $adgroup_id = $this->_get("adgroup_id");
        ParamsCheckUtils::checkNumeric( $adgroup_id , "请输入删除推广组的id");
        $adgroupMdl = new AdgroupModel;
        $ret = $adgroupMdl->removeAdgroup($this->me['user_id'], $adgroup_id);
        if($ret){
            $this->display_json( array('result' => true , 'adgroup_id' => $adgroup_id) );
        }else{
            $this->display_json( array('result' => false , 'msg' => "删除出现错误") );
        }
    }
    
    /**
     * 开启/暂停推广组
     */
    public function pause()
    {
        $adgroup_id = $this->_get("adgroup_id");
        ParamsCheckUtils::checkNumeric( $adgroup_id , "请输入删除推广组的id");
        $adgroupMdl = new AdgroupModel;
        $adgroup = $adgroupMdl->getAdgroupByAdgroupId($this->me['user_id'] , $adgroup_id,false);

        if( !$adgroup ){
            throw new NewzanException('找不到推广组' , RetStatus::PARAM_ERR); 
        }

        //$action = $adgroup['online_status'] == 'online' ? 'offline': 'online';
        $action = $this->_get('action');
        $action_str = array('online' => '开启推广组', 'offline' => '暂停推广组');
        if($adgroup['status'] == AdgroupModel::STATUS_UPDATING) {
        	$this->display_json( array('result' => false , 'msg' => '推广组正在进行自动更新中, 暂时无法' . $action_str[$action]) );
        }
        $ret = $adgroupMdl->pauseOrOpenAdgroup($this->me['user_id'] , $adgroup_id , $action);
        if($ret){
            $this->display_json( array('result' => true , 'adgroup_id' => $adgroup_id , 'action' => $action) );
        } else {
            $this->display_json( array('result' => false , 'msg' => $action_str[$action] . "失败") );
        }       
    }
    
    public function setting()
    {
    	$user_id = $this->me['user_id'];
        $adgroup_id = $this->_get('adgroup_id');   
        ParamsCheckUtils::checkNumeric( $adgroup_id , "请输入删除推广组的id");
        $adgroupMdl = D('Adgroup');
        $adgroup = $adgroupMdl->getAdgroupByAdgroupId($this->me["user_id"] , $adgroup_id, false);
        if(!$adgroup) 
        	throw_exception('推广计划不存在.');
        $campaignMdl = D('Campaign');
        $campaign = $campaignMdl->getCampaignById($this->me["user_id"] , $adgroup["campaign_id"]);
        $creativeMdl = D('Creative');
        $creatives = $creativeMdl->getCreativesByAdgroupId($this->me["user_id"] , $adgroup["adgroup_id"] , true);
        $rptMdl = new RptAdgroupCreativeModel();
        $labels = RptBaseModel::$LABELS;
        $indicators = array (
                "impressions",
                "click",
                "cost",
                "cpc",
                "click",
                "ctr",
                //"roi",
                "sales",
                //"avgpos",
                //"direct_pay_count",
                //"indirect_pay_count",
               // "fav_item_count",
        );
        foreach($creatives as &$creative){
        	if(substr($creative['img_url'],-8)=='_sum.jpg'){
        		$creative['img_url']=substr($creative['img_url'],0,-8);
        	}
        	$index=strpos($creative['img_url'],'uploaded/');
        	$creative['img_name']=substr($creative['img_url'],$index);
        	$report = $rptMdl->getCreativesStats($this->me['user_id'],$creative['campaign_id'] , $creative['adgroup_id'], $creative['creative_id'] , $indicators);
        	foreach( $report['summary'] as $k => $v){
        	    if(isset(RptBaseModel::$LABELS[$k])) { // 只处理统计指标, adgroup_id, campaign_id之类的冗余信息无需处理
        	        $stats[$k] = array(
        	                'num' => ($k=='ctr' ? "$v%": $v),
        	                'label' => $labels[$k],
        	        );
        	        $stats[$k]['series'] =  join(',', array_column($report['series'][ $labels[$k] ], 1));
        	    }
        	}
        	
        	$creative['report'] = $stats;
        }
        
        $creative = count($creatives) > 0 ? array_pop($creatives) : null;
        $creative_other = count($creatives) > 0 ? array_pop($creatives) : null;
        $productMdl = D('Product');
        $product = $productMdl->getProductById($adgroup['num_iid']);
        $imgs = json_decode($product['item_imgs'] , true);
        if(empty($imgs)){
            $imgs[] =$product['pic_url'];
        } else {
            array_unshift($imgs, $product['pic_url']);
        }
        foreach($imgs as &$img){
            $u = $img;
            $img=array();
        	$index=strpos($u,'uploaded/');
            $img['img_name']=substr($u,$index);
        	$img['url']=$u;
        }
        $this->product = $product;
        $this->creative = $creative;
        $this->creative_other = $creative_other;
        $this->campaign = $campaign["campaign"];
        $this->adgroup = $adgroup;
        $this->imgs=$imgs;
        $this->display();
    }
    
    public function manage()
    {
    	$user_id = $this->me['user_id'];
    	$adgroup_id = $this->_get('adgroup_id');
    	ParamsCheckUtils::checkNumeric( $adgroup_id , "请输入推广组的id");
        $this->loadJS('custom.affix', 'custom.appbar','daterangepicker', 'date', "jquery.sparkline", "template", "msg/msg",
            "component/component.tabs", "component/component.keyword.selector" , "component/component.keyword.manager","component/component.action.log",
            'adgroup/detail', 'adgroup/creatives', 'adgroup/report', 'adgroup/keywords');
        $adgroupMdl = new AdgroupModel();
        $adgroup = $adgroupMdl->getAdgroupByAdgroupId($this->me["user_id"] , $adgroup_id, false);
        if(!$adgroup){
        	$this->error("指定的推广组不存在.");
        }
        $campaignMdl = D('Campaign');
        $campaign = $campaignMdl->getCampaignById($this->me["user_id"] , $adgroup["campaign_id"]);
        $this->campaign = $campaign["campaign"];
        $productMdl = D('Product');
        $product = $productMdl->getProductById($adgroup["num_iid"]);
        //get product cat name
        $category_ids = preg_split('/ /', $adgroup['category_ids']);
        if($category_ids){
            $prodcutCates = array();
            foreach($category_ids as $category_id){
                $category = $productMdl->getCatNameByCatId($category_id,false);
                if($category){
                    $prodcutCates[] = $category['cat_name'];
                }
            }
            $product['cats'] = join('>', $prodcutCates);
        }
        //get stat information
        $this->product = $product;
        $adgroup['max_price']= $adgroup['limit'] * 0.01;
        $this->adgroup = $adgroup;
        $this->is_admin = session('admin') ? 1 : 0;

        //无限养分关键词页面无数据弹窗提醒
        $where = array(
            'user_id' => $this->me['user_id'],
            'compaign_id' => $this->campaign['campaign_id'],
            'product_id' => $this->product['num_iid'],
            'adgroup_id'=>$this->adgroup['adgroup_id']
        );
        // dump($where);die;
        $keywordsMdl = M('adgroups');
        $gost = $keywordsMdl->where($where)->getField('drive_type');
        // dump($gost);
        $smartMdl = M('auto_pro_product_queue');

        $gost1 = $smartMdl->where($where)->getField('initial_keyword_count');
        // dump($gost1);die;
           $ismostkeywords = true; 
        if($gost == 2 && $gost1 == 0){
            $ismostkeywords = false;
        }

        $this->mostkeywords = $ismostkeywords;
        // dump($this->mostkeywords);die;

        $this->display();            



        
    }
    
    public function report()
    {
        $adgroup_id = $this->_request( 'adgroup_id');
        $from  = $this->_request('from');
        $to = $this->_request('to');
        ParamsCheckUtils::checkNumeric($adgroup_id);
        $rptAdgroupMdl = new RptAdgroupModel;
        $indicators = array (
                "impressions",
                "click",
                "cost",
                "cpc",
                "click",
                "ctr",
                "cpm",
                "roi",
                "direct_pay",
                "indirect_pay",
                "sales",
                //"direct_pay_count",
                //"indirect_pay_count",
                "fav_shop_count",
                "fav_item_count",
                //"avgpos"
        );

        $from = $from ? $from : date('Y-m-d', time() - 30 * 86400);
        $to = $to ?  $to : date('Y-m-d', time() - 86400);
        $rpt = $rptAdgroupMdl->getAllAdgroupStat( $this->me['user_id'] , $adgroup_id,
            	 		$indicators, $from , $to, 'summary,series' );
        
        $labels = RptBaseModel::$LABELS;
        $stats = array();
        $summary = $rpt["summary"];
        foreach( $summary as $k => $v){
            if(isset(RptBaseModel::$LABELS[$k])) { // 只处理统计指标, adgroup_id, campaign_id之类的冗余信息无需处理
                $stats[$k] = array(
                        'num' => ($k=='ctr' ? "$v%": $v),
                        'label' => $labels[$k],
                );
                switch( $labels[$k] ){
                    case '销售额':
                    case '直接成交额':
                    case '花费':
                        $stats[$k]['css'] = 'orange';
                        $stats[$k]['num'] = '￥' . $stats[$k]['num'];
                        break;
                    default:
                        $stats[$k]['css'] = '';
                        break;
                }
                $stats[$k]['series'] =  join(',', array_column($rpt['series'][ $labels[$k] ], 1));
            }
        }
        // 设置stats显示的顺序
        $this->order_list = array(
                'impressions',	'cpm',
                'click', 		'ctr',
                'cost', 		'cpc',
                'direct_pay', 	'roi',
                'sales', 		'fav_shop_count',
                'indirect_pay', 'fav_item_count',
        );        
        
        $this->stats = $stats;
        $this->display();
    }
    
    public function review()
    {
    	$user_id = $this->me['user_id'];
    	$adgroup_id = $this->_get('adgroup_id');
    	ParamsCheckUtils::checkNumeric( $adgroup_id , "请输入推广组的id");
    	$adgroupMdl = D('Adgroup');
    	$adgroup = $adgroupMdl->getAdgroupByAdgroupId($user_id, $adgroup_id, false);
    	if(!$adgroup){
    		$this->error("推广组不存在.");
    	}
    	
        $res = D('auto_pro_product_queue')->where( 'adgroup_id=' . $adgroup_id )->find();
        if($res){
            $adgroup['limit'] = $res['default_price']; 
        }else{
            $adgroup['limit'] = 0;
        }
    	
    	$this->adgroup = $adgroup;
    	// $this->stats = $stats;
    	// $this->from = $from;
    	// $this->to = $to;
    	$this->display();
    }
    
    public function auto()
    {
    	$items = $this->_get('items');
    	$items = explode(',', $items);
    	//check $item 是否为空
    	ParamsCheckUtils::checkNULL($items , '参数值不能为空');
    	
    	$pq_mdl = new ProductQueueModel;
    	$products = $pq_mdl->getAutoDriveProducts($this->me['user_id'], $items);
        $this->display_json( array('result' => true , 'products' => $products) );
    }
    
    public function autoremove()
    {
    	$user_id = $this->me['user_id'];
        $product_id = $this->_get('product_id');
        $campaign_id = $this->_get('campaign_id');
        ParamsCheckUtils::checkNumeric($product_id , '产品ID不能为空');
        ParamsCheckUtils::checkNumeric($campaign_id , '推广计划ID必须为数字ID');

        $pq_mdl = new ProductQueueModel();
        $deleted_record = $pq_mdl->removeRecord($user_id, ProductQueueAct::MANUAL_DEL, $product_id, $campaign_id);
        if($deleted_record) {
        	$adgroupMdl = new AdgroupModel;
        	$adgroupMdl->removeAdgroup($user_id, $deleted_record['adgroup_id'], true);
        	$data = array('result' => true);
        } elseif($deleted_record === false) {
        	$data = array(
        			'result' => false,
        			'msg' => '正在智能设置中, 无法取消'
        	);
        } else {
        	$data = array(
        			'result' => false,
        			'msg' => '要删除的记录不存在'
        	);
        }
        $this->display_json($data, $data['result'] ? RetStatus::OK : RetStatus::PARAM_ERR);
    }	
    
    public function autoconfirm()
    {
    	$user_id = $this->me['user_id'];
    	$product_id = $this->_get('product_id');
    	$campaign_id = $this->_get('campaign_id');
        ParamsCheckUtils::checkNumeric($product_id , '产品ID必须为数字ID');
        ParamsCheckUtils::checkNumeric($campaign_id , '推广计划ID必须为数字ID');
        
    	$whr = array(
    			'user_id' => $user_id,
    			'product_id' => $product_id,
    			'campaign_id' => $campaign_id,
    	);
    	$rec = M('auto_pro_product_queue')->where( $whr )->find() ;
    	$data = array();
    	if($rec && $rec['status'] != 1){
    		M('auto_pro_product_queue')->where( $whr )->save(array('need_confirm'=>2));
    	
    		// 确认已经创建的adgroup
    		if($rec['adgroup_id']) {
    			$adgroupMdl = new AdgroupModel;
    			$adgroupMdl->pauseOrOpenAdgroup($user_id, $rec['adgroup_id'], 'online', true);
    			
    			$data = array('result' => true);
    			$this->display_json( $data );
    		} else {
	    		$data = array('result' => false, 'msg' => '内部错误.');
	    		$this->display_json( $data, RetStatus::INNER_ERR );
    		}
    	}else{
    		$data = array(
    				'result' => false,
    				'msg' => $rec ? '正在智能设置中, 无法取消' : '找不到该记录'
    		);
    		$this->display_json($data, RetStatus::PARAM_ERR);
    	}
    }
    
    public function detail()
    {
        $adgroup_id = $this->_get('adgroup_id');
        ParamsCheckUtils::checkNumeric($adgroup_id , '推广组ID必须为数字ID');
        $adgroup = D("Adgroups")->where("adgroup_id=" . $adgroup_id)->find();
        $adgroup["cats_str"] = '';
        $this->product = D("Products")->where( array("product_id" => $adgroup["num_iid"]) )->find();
        $this->campaign = D("Campaign")->getCampaignInfo($this->me["user_id"] , $adgroup["campaign_id"]);
        $this->adgroup = $adgroup;
        $this->display();
    }
    
    public function keywords()
    {
        $adgroup_id = $this->_get('adgroup_id');
        $product_id = $this->_get('product_id');
        $category_id = $this->_get('category_id');
        $campaign_id = $this->_get('campaign_id');
        $action_type = $this->_get('action_type');
        $type = $this->_get('type')?$this->_get('type'):1;
        ParamsCheckUtils::checkNumeric($adgroup_id , '必须输入推广组ID');
        // ParamsCheckUtils::checkNumeric($product_id , '必须输入产品ID');
        // ParamsCheckUtils::checkNumeric($category_id ,'必须输入商品分类ID');
        ParamsCheckUtils::checkNumeric($campaign_id , '必须输入推广计划ID');
        $this->autowords_disabled = true;
        $this->category_id = $category_id;
        $this->adgroup_id = $adgroup_id;
        $this->product_id = $product_id;
        $this->campaign_id = $campaign_id;
        $this->adgroup_mobile_discount = floatval(M('adgroups')->where(array('adgroup_id' => $adgroup_id))->getField('mobile_discount/100 AS mobile_discount'));
        $this->type=$type;

        // 获取操作的时间
        $skName = "{$action_type}_time{$this->me['user_id']}-{$adgroup_id}";
        $this->time_search = session('?'.$skName) ? session($skName) : array('from'=> date('Y-m-d', strtotime('-1 day')),'to'=>date('Y-m-d', strtotime('-1 day')));
        $this->display();   
    }
    
    public function addkeywords()
    {
        $this->loadJS('custom.appbar','daterangepicker', 'date', "custom.currency" , "jquery.sparkline.min" , "component/component.keyword.selector" , "custom.keywordmanager" , 'bootstrap-affix');
        $this->adgroup_id = $this->_request('adgroup_id');
        $this->category_id = $this->_request('category_id');
        ParamsCheckUtils::checkNumeric($adgroup_id , '必须输入推广组ID');
        ParamsCheckUtils::checkNumeric($category_id ,'必须输入商品分类ID');
        $this->display();
    }
    
    public function switchauto()
    {
    	$adgroup_id = $this->_post('adgroup_id');
    	$is_auto = $this->_post('is_auto');
    	$smart_type = 1;
    	$max_price = $this->_post('max_price');
    	$drive_type = $is_auto ? 1 : 0;
    	ParamsCheckUtils::checkNumeric($adgroup_id);
    	$user_id = $this->me['user_id'];
    	$adgroupMdl = new AdgroupModel();
    	$existentAdgroup = $adgroupMdl->getAdgroupByAdgroupId($user_id, $adgroup_id, false);
        $drive = array(
            'drive_type' => $drive_type,
        );
        $url_drive = build_url("sinbadgateway/users/{$existentAdgroup['user_id']}/adgroups/{$existentAdgroup['adgroup_id']}");
    	$this->http->setOpt(CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        $this->http->setOpt(CURLOPT_INFILESIZE,16);
       $result = $this->http->put($url_drive,json_encode($drive));
       if($result){
           $this->display_json(array('msg'=>'切换成功!'));
       }else{
           $this->display_json(array('msg'=>'切换失败!'));
       }          
    }

    public function switchautoadd()
    {
    	$user_id = $this->me['user_id'];
    	$adgroup_id = $this->_post('adgroup_id');
    	//// 检查推广计划是否开启
    	$adgroupMdl = new AdgroupModel();
    	$adgroup =  $adgroupMdl->getAdgroupByAdgroupId($user_id, $adgroup_id);
    	if($adgroup['online_status']!='online'){
    		$this->display_json( array('msg' => '推广组暂停，不需要维护') );
    	}
    	$campaignMdl = new CampaignModel();
      	$campaign = $campaignMdl->getCampaignById($user_id , $adgroup['campaign_id'],false);
       	if($campaign["campaign"]['online_status']!='online'){
        	$this->display_json( array('msg' => '推广计划暂停，不需要维护') );
       	}
        
		// 检查是否达到更新周期
		if(2* 86400 + strtotime($adgroup['maintained_date']) > date2time())
			$this->display_json( array('msg' => '上次维护在两天以内，不需要维护') );
		$productQMdl=new ProductQueueModel();
		$pqProduct = $productQMdl->getItem($adgroup['num_iid'], $adgroup['campaign_id']);
		// 自动提交关键词的时候也要更新其状态
		$adgroupMdl->updateStatus($adgroup_id, AdgroupModel::STATUS_UPDATING);
		$autoDrvMdl = new AutoDriveV2Model();
		try {
			$wordsToUpdate=$autoDrvMdl->init($adgroup, $user_id, $pqProduct)
							->maintainAdgroupKeywords();
			$keywordMdl=new KeywordModel();
			$keywordMdl->updateKeywords(0, $wordsToUpdate, null, true);
			$adgroupMdl->updateStatus($adgroup_id, AdgroupModel::STATUS_IDLE, 
							AdgroupModel::STATUS_UPDATING, true);
			$this->display_json( array('msg' => '自动维护完成') );
					
		} catch (Exception $e) {
			$adgroupMdl->updateStatus($adgroup_id, AdgroupModel::STATUS_IDLE,
							AdgroupModel::STATUS_UPDATING, false);
			$this->display_json( array('msg' => '自动维护出错') , RetStatus::INNER_ERR);
		}
    }
    
    public function setauto()
    {
    	$adgroup_id = $this->_post('adgroup_id');
    	$smart_type = $this->_post('smart_type');
    	$max_price = $this->_post('max_price');
    	ParamsCheckUtils::checkNumeric($adgroup_id);
    	$user_id = $this->me['user_id'];
    	$adgroupMdl = new AdgroupModel();
	   	$existentAdgroup = $adgroupMdl->getAdgroupByAdgroupId($user_id, $adgroup_id, false);
	   	$currSucc = false;
	   	if( $existentAdgroup['status'] == AdgroupModel::STATUS_UPDATING  ){
	   		$msg = '原因: 当前推广组正在进行自动更新. 请稍后再设置.';
	   	} else {
	   		$currSucc = $adgroupMdl->setAdgroupAuto( $this->me['user_id'], $existentAdgroup , $smart_type,$max_price);
	   		$msg = '自动开车设置' . ($currSucc ? '成功' : '失败') . '. ';
	   	}
	   		
	   	if($currSucc){
	   		$ret_data['drive_type'] = $smart_type;
	   		$drive_labels = array(
	   				1 => '精细推广',
	   				2 => '高速模式',
	   				3 => '经济模式',
	   				4 => '低价引流'
	   		);
	   		$ret_data['drive_type_str'] = $drive_labels[ $smart_type ];
	   		$this->display_json( $ret_data );
	   	}else{
	   		$this->display_json( array('msg' => '切换开车类型错误') , RetStatus::INNER_ERR);
	   	}
    }

       //修改最高限价
    public function updatePrice(){
        $user_id = $this->me['user_id'];
        $adgroup_id = $this->_post('adgroup_id');
        $limit = $this->_post('limit');
        $adgroupMd = M('adgroups');
        $where['adgroup_id'] = $adgroup_id;
        $mate['limit'] = $limit * 100;
        $result = $adgroupMd->where($where)->save( $mate );
        if($result){
            $this->display_json(array('msg'=>'修改成功!'));
        }
    }

    public function update()
    {
    	$user_id = $this->me['user_id'];
        $adgroup_id = $this->_post('adgroup_id');
        $smart_type = $this->_post('smart_type');
        $limit = $this->_post('limit');
      //  $limit *= 100;
        ParamsCheckUtils::checkNumeric($adgroup_id,'必须输入推广组ID');
        $online_status_open = $this->_post('online_status_open');
        $online_status = $online_status_open ? 'online' :  'offline';
        
        $is_manual_drive = $this->_post('is_manual_drive');
        $drive_type = $is_manual_drive ? AdgroupModel::DRIVE_TYPE_MANUAL : AdgroupModel::DRIVE_TYPE_AUTO;
        $default_price = $this->_post("default_price");
        
        $catmatch_id = $this->_post( "catmatch_id" );
        // $catmatch_open = $this->_post('catmatch_open');
        // $catmatch = $catmatch_open ? 'online' :  'offline';
        // $catmatch_price = $this->_post( "catmatch_price" );
        
        if($default_price !== null) {
	        $default_price = getPriceofCent($default_price);
	        ParamsCheckUtils::checkMinValue( $default_price, 5 , '默认出价不得小于5分');
        }
    	if($limit !== null) {
	        $limit = getPriceofCent($limit);
	        ParamsCheckUtils::checkMinValue( $limit, 5 , '关键词最高出价不得小于5分');
        }
        
		// check adgroup existence
        $succ = true;
        $msg = '';
        $ret_data = array(); // 返回data: 成功更新的新值
        $adgroupMdl = new AdgroupModel();
        $existentAdgroup = $adgroupMdl->getAdgroupByAdgroupId($user_id, $adgroup_id, false);

        if( $existentAdgroup ){
        	$keywordMdl=new KeywordModel();
        	$autoProdMdl=new ProductQueueModel();
        	$exitentAutoP=$autoProdMdl->getItem(Null, NULL, $adgroup_id);
        	if($exitentAutoP['default_price']!=$limit){
            	D('auto_pro_product_queue')->where( 'adgroup_id=' . $adgroup_id)->save( array('default_price' => $limit ) );
            	//加限价后立即更新生效    
            	if($limit > 0 && ($limit < $exitentAutoP['default_price']||$exitentAutoP['default_price']==0)) {     	
    				$keywordMdl->updateKeywordsPriceToLimit($user_id,$adgroup_id,$limit);
            	}
        	}
        }

        if(!$existentAdgroup) {
        	$this->display_json(array('result'=>false, 'msg'=>'推广组不存在.'), RetStatus::PARAM_ERR);
        }
        
        try {
        	// update default price
        	if($default_price !== null && $existentAdgroup['default_price'] != $default_price) {
	            $data['default_price'] = $default_price;
	            $succ = $adgroupMdl->updateAdgroup($user_id , $adgroup_id , $data, $drive_type == AdgroupModel::DRIVE_TYPE_AUTO);
	            $msg = '默认出价更新' . ($currSucc ? '成功' : '失败') . '. ';
	            if($succ) {
	            	$ret_data['default_price'] = $default_price;
	            }
        	}
	        $this->display_json(array_merge($ret_data, array("result" => $succ, 'msg' => $msg)));
        } catch (TopClientException $e) {
        	if(getTopError($e->getMessage() == '指定的推广组不存在')) {
        		$adgroupMdl->removeAdgroupFromDb($user_id, $adgroup_id, $campaignId);
        		$this->display_json(array("result" => false, 'msg' => 'Oooops! 该推广组已经不存在了。'), RetStatus::INNER_ERR);
        	}
        }
    }

    public function updatecreatives()
    {
    	$adgroup_id = $this->_post('adgroup_id');
    	$creative_ids = $this->_post("creative_id");
    	ParamsCheckUtils::checkNumeric($adgroup_id,'必须输入推广组ID');
    	// ParamsCheckUtils::checkNumeric(creative_id,'必须输入创意ID');
    	$titles = $this->_post('title');
    	//检查title长度
    	foreach($titles as $t){
    	    ParamsCheckUtils::checkMaxLength($t, 20, '每个创意标题的最大长度不能超过20个汉字', true);
    	}
            	
    	$img_urls = $this->_post('img_url');
    	$user_id = $this->me['user_id'];
    
    	try {
    		$adgroupMdl = D('Adgroup');
    		$existentAdgroup = $adgroupMdl->getAdgroupByAdgroupId($user_id, $adgroup_id, false);
    		if(!$existentAdgroup) {
	        	$this->display_json(array('result'=>false, 'msg'=>'推广组不存在.'), RetStatus::PARAM_ERR);
	        }
    		 
    		//first if anything changes , update the creatives;
    		$creativeMdl = new CreativeModel();
    		$existentCreatives = $creativeMdl->getCreativesByAdgroupId($user_id, $adgroup_id, false);
    		foreach($existentCreatives as $key =>$creative) {
    			$existentCreatives[$creative['creative_id']] = $creative;
    			unset($existentCreatives[$key]);
    		}
    		
    		while(count($creative_ids) < 2){
    			$creative_ids[] = 0;
    		}
    		
    		$creatives = array();
    		foreach($creative_ids as $k => $creative_id){

    			$creative = array();
    			$creative["title"] = trim($titles[$k]); 
    			$creative["img_url"] = trim($img_urls[$k]);
    			$creative['adgroup_id'] = $adgroup_id;
    			if(empty($creative["title"]) && $creative_id){//如果title为空, 删除该创意
    				$creativeMdl->deleteCreative($user_id ,$adgroup_id, $creative_id);
    				continue;
    			}
    			if(empty($creative["title"]) || empty($creative["img_url"])){ // 为空时更新API会出错
    				if(empty($creative["title"]) && empty($creative["img_url"])){
    					continue;
    				} else {
	    				throw new TopClientException('创意图片或推广标题不能为空' , RetStatus::TOP_API_ERR);
    				}
    			}
    			if($creative_id){
    				$creative['creative_id'] = $creative_id;
    				
    				$existCreative = isset($existentCreatives[$creative_id]) ? $existentCreatives[$creative_id] : null;
    				if($existCreative) 
    					$existCreative['img_url'] = substr($existCreative['img_url'], 0, strlen($existCreative['img_url']) - 8); // remove '_sum.jpg'
    				$diff = $existCreative ? array_kv_diff($existCreative, $creative) : $creative;
    				
    				if($diff)
    					$creativeMdl->updateCreative($user_id, $creative, false, $diff);
    			}else{
    				$creative = $creativeMdl->addCreative($user_id, $adgroup_id, $creative);
    			}
    			$creatives[] = $creative;
    		}
    		 
    		$this->display_json( array("result" => true, 'creatives' => $creatives ) );
    	} catch (Exception $e) {
    		throw new TopClientException( $e->getMessage() , RetStatus::TOP_API_ERR);
    	}
    }
    
    public function add()
    {
    	$user_id = $this->me["user_id"];
        $product_id = (float) $this->_post("product_id");
        ParamsCheckUtils::checkNumeric($product_id,'必须输入产品ID');

        $campaign_id = (float) $this->_post("campaign_id");
        $budget = $_POST['budget'];
        $limit = $_POST['limit'];
        $budget = (float) str_replace( "￥" , "" ,$budget) ;
        $limit = (float) str_replace("￥" , "" , $limit);
        $limit = $limit * 100;

        $adgroup_obj = new AdgroupModel();
        if( $adgroup_obj->hasAdgroup($product_id , $campaign_id) ){
            $this->display_json( array( 'msg' => '该商品正在推广中') , RetStatus::INNER_ERR);
        }

        $adgroup = array(
            'product_id' => $product_id,
            'product_url' => $this->_post("picture"),
            'title' => $this->_post("title"),
            'campaign_id' => $campaign_id,
            'default_price' => $limit,
			'budget' =>$budget,
             "creative_title" =>$this->_post("creative_title"),
            "creative_img_url" =>$this->_post("creative_img_url")
        );
        $url_campaign = build_url("sinbadgateway/users/{$user_id}/adgroups");
        $this->http->setOpt(CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
        $result = $this->http->post($url_campaign,json_encode($adgroup));
        $test = object_to_array($result);
         if($test['status'] == 500){
            if( $test['message'] == 'adgroup.item.not.online'){
                 $this->display_json(array('msg'=>'对不起,该商品已下架,请您选择其他商品!'),RetStatus::INNER_ERR);
            }else{
                $this->display_json(array('msg'=>'系统又调皮,开小差了!'),RetStatus::INNER_ERR);
            }
            die;
        }else{
             $this->display_json(array('msg'=>'添加成功！','adgroup_id'=>$result->adgroup_id));
        }
    }
 
    public function log()
    {
	    $campaign_id = $this->_get('campaign_id');
		$adgroup_id = $this->_get('adgroup_id');
		$page = $this->_get('page');
		$page = $page ? $page : 1;
		$logs = array();
		//1. get adgroup logs
		 $adgroupMdl = new AdgroupModel();
		$adgroup_logs = $adgroupMdl->getLogs($this->me['user_id'] , 'adgroup_id' , $adgroup_id, null, null, true);
		$logs = $adgroup_logs;
		//2. get adgroup keyword log
		$keywordMdl = new KeywordModel();
		$keyword_logs = $keywordMdl->getLogs($this->me['user_id'] , 'adgroup_id' , $adgroup_id );
		$logs = array_merge($keyword_logs, $logs);
		//3. get creative logs
		$creativeMdl = new CreativeModel();
		$creative_logs = $creativeMdl->getLogs($this->me['user_id'], 'adgroup_id', $adgroup_id);
		//$logs += $creative_logs;
		$logs = array_merge($logs, $creative_logs);
        //4. sort logs
        usort( $logs , uc_cmp_log_desc);
        $pageSize = 10;
        $paged_logs = array_slice( $logs, $pageSize * ($page - 1) , $pageSize);
        $has_next = ($pageSize * $page) < count($logs) ? 1 : 0;
        $res = array(
            'logs' => $paged_logs,
            'current_page' => $page,
            'has_next' => $has_next
        );
        $this->display_json( $res );
    }
    
    
    public function boundary()
    {
    	$params = $_POST;
        $sourceType = (isset($params['platform']) && in_array($params['platform'], array(0,1,2)))? self::$source[$params['platform']] : self::$source[0] ; // 0 summary , 1 pc , 2 wireless
    	$adgroup_id = $params['adgroup_id'];
    	ParamsCheckUtils::checkNumeric($adgroup_id,'必须输入推广组ID');
    	ParamsCheckUtils::checkDate($params['from']);
    	ParamsCheckUtils::checkDate($params['to']);
    	//$params['from'] = date('Y-m-d' ,  strtotime( '-90 day'));
    	$keywordMdl = new KeywordModel();
    	$boundary = $keywordMdl->getStatsBoundary('adgroup_id', $adgroup_id , $params['from'], $params['to'], $sourceType);
    	foreach( $boundary as $ic => $value){
    		switch($ic){
    			case 'cpc':
    			case 'cpm':
    			case 'ctr':
    			case 'cvr':
    				$max = ceil( $value * 100 );
    			break;
    			
    			default:
    				$max = ceil( $value );
    			break;
    		}
    		$boundary[$ic] = array(
    					'min' => 0,
    					'max' => $max
    				);
    	}
    	$this->display_json( array('params' => array( 'filter' => $boundary ) ) );
    }
}
